package com.lanou.connotationjoke.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.connotationjoke.view.NewListView;
import com.lanou.connotationjoke.R;
import com.lanou.connotationjoke.view.RefreshableView;
import com.lanou.connotationjoke.adapter.HomeVideoListViewAdapter;
import com.lanou.connotationjoke.db.HomeVideoEntity;
import com.lanou.connotationjoke.db.HomeVideoEntityDao;
import com.lanou.connotationjoke.entity.AppUrl;
import com.lanou.connotationjoke.entity.CommentEty;
import com.lanou.connotationjoke.entity.CurrentItemEty;
import com.lanou.connotationjoke.entity.DataDetialEty;
import com.lanou.connotationjoke.entity.GroupEty;
import com.lanou.connotationjoke.entity.JsonEty;
import com.lanou.connotationjoke.entity.UserEty;
import com.lanou.connotationjoke.tool.DaoSingleton;
import com.lanou.connotationjoke.tool.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;


/**
 * Created by dllo on 16/1/8.
 */
public class HomeVideoFragment extends BaseFragment {
    private NewListView listView;
    private RefreshableView refreshableView;
    private HomeVideoListViewAdapter adapter;
    private List<DataDetialEty> datas;
    private final String URL = AppUrl.HOMEVIDEO;
    private HomeVideoEntityDao homeVideoEntityDao =
            DaoSingleton.getInstance().getHomeVideoEntityDao();
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            EventBus.getDefault().post("stop");
            return false;
        }
    });

    private static boolean isRegister = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_video, container, false);
        listView = (NewListView) view.findViewById(R.id.listview_home_video);
        refreshableView = (RefreshableView) view.findViewById(R.id.refresh_video);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (isRegister == false){
            EventBus.getDefault().register(this);
            isRegister = true;
        }


        VolleySingleton.addRequest(URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                JsonEty jsonEty = gson.fromJson(response, JsonEty.class);
                if (null != jsonEty&&null != jsonEty.getData()){
                    datas = jsonEty.getData().getData();
                }
                adapter = new HomeVideoListViewAdapter(getActivity(), datas);
                listView.setAdapter(adapter);
                insertOrReplaceToHomeVideoDao(datas);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                datas = getDataFromHomeVideoDao();
                adapter = new HomeVideoListViewAdapter(getActivity(), datas);
                listView.setAdapter(adapter);
            }
        });

        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
           VolleySingleton.addRequest(URL, new Response.Listener<String>() {
               @Override
               public void onResponse(String response) {
               Gson gson = new Gson();
                   JsonEty jsonEty = gson.fromJson(response,JsonEty.class);
                   datas = jsonEty.getData().getData();
                   adapter.refreshData(datas);
                   insertOrReplaceToHomeVideoDao(datas);
                   refreshableView.finishRefreshing();
                   handler.sendEmptyMessage(0);
               }
           }, new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
                   handler.sendEmptyMessage(0);
                   refreshableView.finishRefreshing();
               }
           });
            }
        },1);




        }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        isRegister = false;
    }


    /**
     *
     * @param currentItemEty
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onMainEvent(CurrentItemEty currentItemEty) {
        if (currentItemEty.getI() == 1){
            listView.setSelection(0);
            new Thread() {
                @Override
                public void run() {
                    final long downTime = SystemClock.currentThreadTimeMillis();

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent down = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_DOWN, 10, 300, 0);
                            listView.dispatchTouchEvent(down);
                        }
                    });


                    SystemClock.sleep(50);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent move = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_MOVE, 10, 700, 0);
                            listView.dispatchTouchEvent(move);
                        }
                    });


                    SystemClock.sleep(50);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent move = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_MOVE, 10, 1000, 0);
                            listView.dispatchTouchEvent(move);
                        }
                    });

                    SystemClock.sleep(1000);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent up = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_UP, 10, 1000, 0);
                            listView.dispatchTouchEvent(up);
                        }
                    });
                }
            }.start();


        }

    }







    private void insertOrReplaceToHomeVideoDao(List<DataDetialEty> datas) {
        homeVideoEntityDao.deleteAll();
        for (DataDetialEty dataDetialEty : datas) {
            if (dataDetialEty.getGroup() != null) {
                String avatar_url = dataDetialEty.getGroup().getUser().getAvatar_url();
                String name = dataDetialEty.getGroup().getUser().getName();
                String content = dataDetialEty.getGroup().getContent();
                String category_name = dataDetialEty.getGroup().getCategory_name();
                String cover_image_uri = dataDetialEty.getGroup().getCover_image_uri();
                String mp4_url = dataDetialEty.getGroup().getMp4_url();
                //TODO ...
                int digg_count = dataDetialEty.getGroup().getDigg_count();
                int bury_count = dataDetialEty.getGroup().getBury_count();
                int comment_count = dataDetialEty.getGroup().getComment_count();
                int share_count = dataDetialEty.getGroup().getShare_count();
                String share_url = dataDetialEty.getGroup().getShare_url();
                int playCount = dataDetialEty.getGroup().getPlay_count();
                String avatar_url_comment = null;
                String user_name_comment = null;
                int digg_count_comment = 0;
                String text_comment = null;
                if (dataDetialEty.getComments().size() > 0) {
                    avatar_url_comment = dataDetialEty.getComments().get(0).getAvatar_url();
                    user_name_comment = dataDetialEty.getComments().get(0).getUser_name();
                    digg_count_comment = dataDetialEty.getComments().get(0).getDigg_count();
                    text_comment = dataDetialEty.getComments().get(0).getText();
                }
                homeVideoEntityDao.insert(new HomeVideoEntity(homeVideoEntityDao.count(), avatar_url, name, content, category_name, cover_image_uri, mp4_url, avatar_url_comment,
                        user_name_comment, digg_count_comment, text_comment, digg_count, bury_count, comment_count, share_count, share_url, playCount));
            }
        }
    }


    private List<DataDetialEty> getDataFromHomeVideoDao() {
        List<DataDetialEty> datas = new ArrayList<>();
        List<HomeVideoEntity> homeVideoEntities = homeVideoEntityDao.queryBuilder().list();
        if (homeVideoEntities == null) {
            return null;
        }
        for (HomeVideoEntity homeVideoEntity : homeVideoEntities) {
            DataDetialEty dataDetialEty = new DataDetialEty();
            GroupEty groupEty = new GroupEty();
            List<CommentEty> commentEties = new ArrayList<>();
            CommentEty commentEty = new CommentEty();
            UserEty userEty = new UserEty();
            userEty.setAvatar_url(homeVideoEntity.getAvatar_url());
            userEty.setName(homeVideoEntity.getName());
            groupEty.setUser(userEty);
            groupEty.setContent(homeVideoEntity.getContent());
            groupEty.setCategory_name(homeVideoEntity.getCategory_name());
            groupEty.setCover_image_uri(homeVideoEntity.getCover_image_uri());
            groupEty.setMp4_url(homeVideoEntity.getMp4_url());
            groupEty.setDigg_count(homeVideoEntity.getDigg_count());
            groupEty.setBury_count(homeVideoEntity.getBury_count());
            groupEty.setComment_count(homeVideoEntity.getComment_count());
            groupEty.setShare_count(homeVideoEntity.getShare_count());
            groupEty.setShare_url(homeVideoEntity.getShare_url());
            groupEty.setPlay_count(homeVideoEntity.getPlay_count());
            if (homeVideoEntity.getAvatar_url_comment() != null) {
                commentEty.setAvatar_url(homeVideoEntity.getAvatar_url_comment());
                commentEty.setUser_name(homeVideoEntity.getUser_name_comment());
                commentEty.setDigg_count(homeVideoEntity.getDigg_count_comment());
                commentEty.setText(homeVideoEntity.getText_comment());
                commentEties.add(commentEty);
            }
            dataDetialEty.setGroup(groupEty);
            dataDetialEty.setComments(commentEties);
            datas.add(dataDetialEty);
        }
        return datas;
    }


}
